<template>
  <BasicModal
    @register="registerModal"
    v-bind="$attrs"
    title="添加部件包"
    ok-text="保存"
    :destroy-on-close="true"
    @ok="handleSubmit"
    :closeFunc="handleClose"
  >
    <BasicForm @register="registerForm">
      <template #upload>
        <Upload
          v-model:fileList="fileList"
          accept=".jpg,.png,.gif,.svg,.bmp,.jpeg,.webp,.ico"
          :maxCount="1"
          :beforeUpload="handleBeforeUpload"
          listType="picture"
        >
          <a-button> 选择图片 </a-button>
        </Upload>
      </template>
    </BasicForm>
  </BasicModal>
</template>

<script setup lang="ts">
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { Upload } from 'ant-design-vue';
  import { schemas } from './addModal.data';
  import { ref } from 'vue';
  import { getWidgetsBundleInfo } from '/@/api/thingsborad/resources/widgets/widgets';
  import { modalFormStyleSetting } from '/@/settings/thingsBoardDesign';
  const emit = defineEmits(['success']);
  const fileList = ref<any>();
  const image = ref<any>();
  const recordInfo = ref<any>();
  const mode = ref<any>();
  const [registerModal, { closeModal, setModalProps }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: true });
    mode.value = data.key;
    if (data.key == 'edit') {
      const info = await getWidgetsBundleInfo(data.id);
      recordInfo.value = info;
      info.image == null
        ? (fileList.value = null)
        : (fileList.value = [
            {
              url: info.image,
            },
          ]);
      setFieldsValue({ ...info });
    }
    setModalProps({ confirmLoading: false });
  });
  const [registerForm, { validate, setFieldsValue, resetFields }] = useForm({
    layout: 'vertical',
    schemas,
    ...modalFormStyleSetting,
    showActionButtonGroup: false,
  });
  const handleClose = async () => {
    resetFields();
    fileList.value = null;
    return true;
  };
  const handleBeforeUpload = (file: File) => {
    const fileReader = new FileReader();
    fileReader.readAsDataURL(file);
    fileReader.onload = async (e) => {
      image.value = e.target?.result;
    };
    return false;
  };
  const handleSubmit = async () => {
    if (mode.value == 'add') {
      const values = await validate();
      emit('success', { values, key: 'add', image: image.value });
      closeModal();
    } else if (mode.value == 'edit') {
      const values = await validate();
      emit('success', { values, key: 'edit', image: image.value, info: recordInfo.value });
      closeModal();
    }
  };
  // onMounted(() => {
  //   setModalProps({
  //     width: '548px',
  //   });
  // });
</script>
